package com.ls.pay.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ls.pay.myAlipay.AlipayConfig;
import com.ls.pay.pojo.AlipayRecord;
import com.ls.pay.pojo.Customer;
import com.ls.pay.pojo.Recharge;
import com.ls.pay.repository.AlipayRecordRepository;
import com.ls.pay.repository.CustomerRepository;
import com.ls.pay.repository.RechargeRrepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static java.lang.System.out;

/**
 * @author 钰杰
 * @className AlipayService
 * @description VX:FengYJ996
 * @date 2020/1/718:55
 */
@Service
public class AlipayService {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private RechargeRrepository rechargeRrepository;

    @Autowired
    private AlipayRecordRepository alipayRecordRepository;

    /**
     * 请求支付宝支付
     *
     * @param httpResponse
     * @return
     * @throws ServletException
     * @throws IOException
     * @throws AlipayApiException
     */
    public HttpServletResponse doPost(Recharge recharge,
                                      HttpServletResponse httpResponse) throws ServletException, IOException, AlipayApiException {

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String wiDout_trade_no = recharge.getOutTradeNo();
        // 订单名称，必填
        String wiDsubject = recharge.getSubject();
        // 付款金额，必填
        String wiDtotal_amount = Double.toString(recharge.getRechargeAmount());
        // 商品描述，可空
        String wiDbody = recharge.getBody();

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        //在公共参数中设置回跳和通知地址
        alipayRequest.setReturnUrl(AlipayConfig.return_url);

        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + wiDout_trade_no + "\","
                + "\"total_amount\":\"" + wiDtotal_amount + "\","
                + "\"subject\":\"" + wiDsubject + "\","
                + "\"body\":\"" + wiDbody + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

        return httpResponse;
    }


    /**
     * 支付异步操作
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Transactional
    public String toNotify(HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        out.println("通知异步处理");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        // 实际验证过程建议商户务必添加以下校验：
        //1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        Recharge byOut_trade_no = rechargeRrepository.findByOutTradeNo(out_trade_no);
        if (StringUtils.isEmpty(byOut_trade_no)) {
            return "fail";
        }
        //2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
        if (!byOut_trade_no.getRechargeAmount().equals(total_amount)) {
            return "fail";
        }
        //3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
        if (!seller_id.equals(AlipayConfig.SELLER_ID)) {
            return "fail";
        }
        //4、验证app_id是否为该商户本身。
        String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "UTF-8");
        if (!app_id.equals(AlipayConfig.APPID)) {
            return "fail";
        }
        if (signVerified) {
            //判断操作标题，做出对应操作。
            this.doWork(request, signVerified, out_trade_no);
            return "success";
        } else {
            return "fail";
        }

    }

    /**
     * 定时查询Alipay交易信息。保证数据库实时交易状态
     */
    public void checkAlipayRecord() throws AlipayApiException {
        List<AlipayRecord> all = alipayRecordRepository.findAll();
        all.forEach(i -> {
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + i.getOut_trade_no() + "\"," +
                    "\"trade_no\":\"" + i.getTrade_no() + "\"," +
                    "}");
            AlipayTradeQueryResponse response = null;
            try {
                response = alipayClient.execute(request);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }

            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
//                switch (tradeStatus) {
//                    case "TRADE_CLOSED":
//                        alipayRecordRepository.updAlipayRecordPayStatus(AlipayConfig.TRADE_CLOSED, i.getAli_recid());
//                        break;
//                    case "TRADE_FINISHED":
//                        alipayRecordRepository.updAlipayRecordPayStatus(AlipayConfig.TRADE_FINISHED, i.getAli_recid());
//                        break;
//                    case "TRADE_SUCCESS":
//                        alipayRecordRepository.updAlipayRecordPayStatus(AlipayConfig.TRADE_SUCCESS, i.getAli_recid());
//                        break;
//                    case "WAIT_BUYER_PAY":
//                        alipayRecordRepository.updAlipayRecordPayStatus(AlipayConfig.WAIT_BUYER_PAY, i.getAli_recid());
//                        break;
//                }
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        });
    }


    /**
     * 生成用户-商城订单
     * subject 1:充值、2:续费
     *
     * @param recharge
     */
    public void addRecharge(Recharge recharge) {
        recharge.setCdate(new Date());
        recharge.setDstatus(1);
        String subject = recharge.getSubject();
        if ("充值用户余额".equals(subject)) {
            recharge.setSubject("1");
        } else if ("用户接口续费".equals(subject)) {
            recharge.setSubject("2");
        }
        rechargeRrepository.save(recharge);
    }

    //验证后各个对应操作
    public void doWork(HttpServletRequest request, boolean signVerified, String out_trade_no) throws UnsupportedEncodingException {
        if (signVerified) {//验证成功
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            //生成支付宝与商户交易信息
            AlipayRecord alipayRecord = new AlipayRecord();
            //成交金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            alipayRecord.setCdate(new Date());
            alipayRecord.setDstatus(0);
            alipayRecord.setOut_trade_no(out_trade_no);
            alipayRecord.setTrade_no(trade_no);

            if (trade_status.equals("TRADE_FINISHED")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                out.println("TRADE_FINISHED:当前交易已结束，不可退款");
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                out.println("TRADE_SUCCESS");
                alipayRecord.setPayStatus(AlipayConfig.TRADE_SUCCESS);
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                //根据订单描述执行本地数据库操作
                //获取操作对象
                Recharge byTradeno = rechargeRrepository.findByTradeno(out_trade_no);
                Customer byAppid = customerRepository.findByAppid(byTradeno.getAppid());
                switch (byTradeno.getSubject()) {
                    case "1"://充值操作
                        double result = byAppid.getBalance() + Double.valueOf(total_amount);
                        customerRepository.updCustomerBalance(byAppid.getAppid(), result);
                        break;
                    case "2":

                        break;
                }
            }
            out.println("success");
            alipayRecordRepository.save(alipayRecord);
//            return "success";
        } else {//验证失败
            out.println("fail");
//            return "fail";
        }
    }

}